<template>
  <el-card class="box-card">
    <div
      slot="header"
      class="clearfix"
    >
      <span>账号列表</span>
    </div>
    <!-- 内容 -->
    <div class="content">
      <el-table
        :data="tableData"
        :style="{ width: w + 'px' }"
        ref="accountTable"
        @selection-change="handlSelectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
        > </el-table-column>
        <el-table-column
          prop="account"
          label="账号"
        > </el-table-column>
        <el-table-column
          prop="userGroup"
          label="用户组"
        > </el-table-column>
        <el-table-column
          prop="ctime"
          label="创建时间"
        >
          <template slot-scope="scope">
            <span>
              {{ scope.row.ctime | formatDatenyrsfm }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <template>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除吗？"
                @confirm="handleDelete(scope.row)"
                @cancel="handleCancel"
              >
                <el-button
                  size="mini"
                  type="danger"
                  slot="reference"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="currentPage"
        :page-sizes="[3, 5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      > </el-pagination>
      <el-button
        size="small"
        type="danger"
        @click="hangdlleBatchDle"
      >批量操作</el-button>
      <el-button
        size="small"
        type="primary"
        @click="cancelSelect"
      >取消选择</el-button>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑账号"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form
        ref="editForm"
        label-width="80px"
        :model="editForm"
        :rules="rules"
      >
        <el-form-item
          label="账号"
          prop="account"
        >
          <el-input
            v-model="editForm.account"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户组">
          <el-select
            v-model="editForm.userGroup"
            style="width: 200px"
          >
            <el-option value="超级管理员">超级管理员</el-option>
            <el-option value="普通管理员">普通管理员</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="dialogVisible = false"
          size="small"
        >取 消</el-button>
        <el-button
          type="primary"
          @click="saveEdit"
          size="small"
        >确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getAccount,
  delAccount,
  editAccount,
  batchDelAccount,
} from "@/api/user";
import { checkAccount } from "@/utils/tools";
export default {
  data() {
    return {
      tableData: [],
      // 表格动态样式
      w: document.body.clientWidth - 300,
      currentPage: 1, //当前页
      pageSize: 3, //数据总条数
      total: 0, //每页条数
      dialogVisible: false,
      // 编辑表单
      editForm: {
        account: "",
        userGroup: "",
      },
      rules: {
        account: [{ validator: checkAccount, trigger: "blur" }],
      },
    };
  },
  methods: {
    // 获取用户列表
    async getUserData() {
      let res = await getAccount({
        currentPage: this.currentPage, //当前页码
        pageSize: this.pageSize, //每页条数
      });
      let { total, data } = res.data;
      // 如果当前页没有数据
      if (!data.length && this.currentPage !== 1) {
        this.currentPage -= 1;
        this.getUserData();
      }
      this.total = total;
      this.tableData = data;
    },
    // 编辑按钮
    handleEdit(row) {
      this.dialogVisible = true;
      let { id, account, userGroup } = row;
      this.editForm = { id, account, userGroup };
    },
    // 保存编辑结果
    async saveEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          this.dialogVisible = false;
          let res = await editAccount(this.editForm);
          let { code } = res.data;
          console.log(res);
          if (code === 0) {
            this.getUserData();
          }
        }
      });
    },
    // 删除按钮
    async handleDelete(row) {
      let res = await delAccount({ id: row.id });
      let { code } = res.data;
      if (code === 0) {
        this.getUserData();
      }
    },
    // 取消删除
    handleCancel() {
      this.$message("取消成功");
    },
    resize() {
      this.w = document.body.clientWidth - 300;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUserData();
    },
    // 取消选择
    cancelSelect() {
      this.$refs.accountTable.clearSelection();
    },
    // 选项发生改变
    handlSelectionChange(rows) {
      this.ids = rows.map((v) => v.id);
    },
    // 批量删除
    hangdlleBatchDle() {
      // 如果客户什么都没选就执行这个操作
      if (!this.ids || !this.ids.length) {
        this.$message.error("选择以后再操作");
        return;
      }

      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await batchDelAccount({ ids: JSON.stringify(this.ids) });
          let { code } = res.data;
          if (code === 0) {
            this.getUserData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },

  created() {
    window.addEventListener("resize", this.resize);
    this.getUserData();
  },
  beforeDestroy() {
    // 组件销毁前移除监听
    window.removeEventListener("resize", this.resize);
  },
};
</script>

<style lang="less" scoped>
.el-button--danger {
  margin-left: 20px;
}
.el-pagination {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
